// 获取个人信息
let token = localStorage.getItem('token')

function hm_getUserInfo() {
  axios
    .get('http://api-breakingnews-web.itheima.net/my/userinfo', {
      headers: {
        Authorization: token,
      },
    })
    .then(res => {
      let { email, id, nickname, user_pic, username } = res.data.data
      console.log('用户信息', email, id, nickname, user_pic, username)

      $('.layui-form input[name=username]').val(username)
      $('.layui-form input[name=nickname]').val(nickname)
      $('.layui-form input[name=email]').val(email)
      $('.layui-form input[name=id]').val(id)
    })
}

hm_getUserInfo()

// 校验
let form = window.layui.form
form.verify({
  nickname: val => {
    if (!/^[\u4E00-\u9FA5]+$/.test(val)) {
      return '昵称必须为中文'
    }
  },
})

// 点击确定
$('.my-update').on('click', e => {
  console.log('点击了确定')

  // 1. 阻止默认行为
  e.preventDefault()

  // 2. 获取值
  let id = $('.layui-form input[name=id]').val()
  let nickname = $('.layui-form input[name=nickname]').val()
  let email = $('.layui-form input[name=email]').val()
  let data = `id=${id}&nickname=${nickname}&email=${email}`

  // 3.  更新
  axios
    .post('http://api-breakingnews-web.itheima.net/my/userinfo', data, {
      headers: {
        Authorization: localStorage.getItem('token'),
      },
    })
    .then(res => {
      console.log('res', res)

      //   刷新
      window.parent.mg_getUserInfo()
    })
})

// 点击重置
$('.my-reset').on('click', () => {
  console.log('重置')

  hm_getUserInfo()
})
